package work.xiaohong.saolei.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import work.xiaohong.model.Result;
import work.xiaohong.model.StatusCode;
import work.xiaohong.saolei.pojo.Dianzhan;
import work.xiaohong.saolei.pojo.Grade;
import work.xiaohong.saolei.pojo.User;
import work.xiaohong.saolei.service.SaoleiDianzhanService;
import work.xiaohong.saolei.service.SaoleiGradeService;
import work.xiaohong.saolei.service.SaoleiUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Tag(name = "SaoleiUser接口文档")
@RestController
@RequestMapping("/saoleiUser")
public class SaoleiUserController {

    @Autowired
    private SaoleiUserService saoleiUserService;

    @Autowired
    private SaoleiGradeService saoleiGradeService;

    @Autowired
    private SaoleiDianzhanService saoleiDianzhanService;

    @Autowired
    private PkController pkController;

    /***
     * 分页条件搜索实现SaoleiUser
     * @param user
     * @param page
     * @param size
     * @return
     */
    @Operation(summary = "条件分页查询SaoleiUser",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @Parameters({
            @Parameter(in = ParameterIn.PATH, name = "page", description = "当前页", required = true),
            @Parameter(in = ParameterIn.PATH, name = "size", description = "每页显示条数", required = true)
    })
    @PostMapping(value = "/search/{page}/{size}" )
    public Result<Page> findPage(@RequestBody(required = false) @Parameter(name = "SaoleiUser对象",required = true) User user, @PathVariable int page, @PathVariable  int size){
        //调用SaoleiUserService实现分页条件查询SaoleiUser
        Page pageInfo = saoleiUserService.findPage(user, page, size);
        return new Result<Page>(true, StatusCode.OK.getCode(),"查询成功",pageInfo);
    }

    /***
     * 分页搜索实现SaoleiUser
     * @param page:当前页
     * @param size:每页显示多少条
     * @return
     */
    @Operation(summary = "分页查询SaoleiUser",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @Parameters({
            @Parameter(in = ParameterIn.PATH, name = "page", description = "当前页", required = true),
            @Parameter(in = ParameterIn.PATH, name = "size", description = "每页显示条数", required = true)
    })
    @GetMapping(value = "/search/{page}/{size}" )
    public Result<Page> findPage(@PathVariable  int page, @PathVariable  int size){
        //调用SaoleiUserService实现分页查询SaoleiUser
        Page pageInfo = saoleiUserService.findPage(page, size);
        return new Result<Page>(true,StatusCode.OK.getCode(),"查询成功",pageInfo);
    }

    /***
     * 多条件搜索SaoleiUser数据
     * @param user
     * @return
     */
    @Operation(summary = "多条件查询SaoleiUser",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @PostMapping(value = "/search" )
    public Result<List<User>> findList(@RequestBody(required = false) @Parameter(name = "SaoleiUser对象",required = true) User user){
        //调用SaoleiUserService实现条件查询SaoleiUser
        List<User> list = saoleiUserService.findList(user);
        return new Result<List<User>>(true,StatusCode.OK.getCode(),"查询成功",list);
    }

    /***
     * 根据Id删除saoleiUser数据
     * @param id
     * @return
     */
    @Operation(summary = "根据ID删除SaoleiUser",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @Parameter(in = ParameterIn.PATH, name = "id", description = "删除对象ID", required = true)
    @DeleteMapping(value = "/{id}" )
    public Result delete(@PathVariable Long id){
        //调用SaoleiUserService实现根据ID删除
        saoleiUserService.delete(id);
        return new Result(true,StatusCode.OK.getCode(),"删除成功");
    }

    /***
     * 根据ID修改SaoleiUser数据
     * @param user
     * @return
     */
    @Operation(summary = "根据ID修改SaoleiUser",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @PutMapping
    public Result updateById(@RequestBody @Parameter(name = "SaoleiUser对象",required = true) User user){
        //调用SaoleiUserService实现修改SaoleiUser
        saoleiUserService.updateById(user);
        return new Result(true,StatusCode.OK.getCode(),"修改成功");
    }

    /***
     * 新增SaoleiUser数据
     * @param user
     * @return
     */
    @Operation(summary = "添加SaoleiUser",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @PostMapping
    public Result add(@RequestBody  @Parameter(name = "SaoleiUser对象",required = true) User user){
        //调用SaoleiUserService实现添加SaoleiUser
        saoleiUserService.add(user);
        return new Result(true,StatusCode.OK.getCode(),"添加成功");
    }

    /***
     * 根据ID查询SaoleiUser数据
     * @param id
     * @return
     */
    @Operation(summary = "根据ID查询SaoleiUser",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @Parameter(in = ParameterIn.PATH, name = "id", description = "查询对象ID", required = true)
    @GetMapping("/{id}")
    public Result<User> findById(@PathVariable Long id){
        //调用SaoleiUserService实现根据ID查询SaoleiUser
        User user = saoleiUserService.findById(id);
        user.setStatus(pkController.getStatus(user.getId()).getData());
        return new Result<User>(true,StatusCode.OK.getCode(),"查询成功", user);
    }

    /***
     * 查询SaoleiUser全部数据
     * @return
     */
    @Operation(summary = "查询所有SaoleiUser",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @GetMapping
    public Result<List<User>> findAll(){
        //调用SaoleiUserService实现查询所有SaoleiUser
        List<User> list = saoleiUserService.findAll();
        return new Result<List<User>>(true, StatusCode.OK.getCode(),"查询成功",list) ;
    }

    /***
     * 更新User数据
     * @param user
     * @return
     */
    @Operation(summary = "更新User数据",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @PutMapping("/update")
    public Result update(@RequestBody @Parameter(name = "SaoleiUser对象",required = true) User user){
        User fu = new User();
        fu.setOpenId(user.getOpenId());
        if (saoleiUserService.findList(fu).size() != 0 && saoleiUserService.findList(fu) != null){
            // 有该用户数据 更新
            saoleiUserService.update(user);
        }else{
            // 添加
            saoleiUserService.add(user);
        }

        // 返回更新后的完整数据
        List<User> list = saoleiUserService.findList(fu);
        if (list.size() == 1){
            User user1 = list.get(0);
            user1.setStatus(pkController.getStatus(user1.getId()).getData());
            return new Result(true,StatusCode.OK.getCode(),"修改成功",user1);
        }else {
            //后台错误
            return new Result(true,StatusCode.ERROR.getCode(),"后台错误",list);
        }

    }


    /***
     * 获取成绩排行榜
     * @return
     */
    @Operation(summary = "获取成绩排行榜",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @Parameter(in = ParameterIn.PATH, name = "model", description = "模式", required = true)
    @GetMapping("/top10/{model}/{player}")
    public Result<List<User>> findTop10Asc(@PathVariable String model,@PathVariable Long player){
        List<User> all = saoleiUserService.findAll();
        for (User user : all) {
            if (StringUtils.isEmpty(user.getBestGrade())){
                // 没有该模式
                user.setRequeryGrade(0F);
            }else {
                // 将最好成绩转为对象
                List<Grade> gradeList = JSONObject.parseArray(user.getBestGrade(), Grade.class);
                // 看看有没有该模式
                boolean flag = true;
                for (Grade grade : gradeList) {
                    if (grade.getModel().equals(model)){
                        //有该模式
                        flag = false;
                        user.setRequeryGrade(grade.getGrade());
                        // 获取该模式该用户总场次
                        Grade gd = new Grade();
                        gd.setPlayer(user.getId());
                        gd.setModel(model);
                        user.setGameTotal(saoleiGradeService.findList(gd).size());
                        break;
                    }
                }

                if (flag){
                    // 没有该模式
                    user.setRequeryGrade(0F);
                }
            }


        }

        // 根据requeryGrade排序
        all.sort(Comparator.comparing(User::getRequeryGrade));

        List<User> resultList  = new ArrayList<User>();
        for (User user : all) {
            if (resultList.size() == 10){
                break;
            }

            if (!user.getRequeryGrade().equals(0F)){
                resultList.add(user);
            }
        }

        // 判断用户是否点赞 并添加状态
        for (User user : resultList) {
            Dianzhan dianzhan = new Dianzhan();
            dianzhan.setProvider(player);
            dianzhan.setReceiver(user.getId());
            if(saoleiDianzhanService.findList(dianzhan).size() > 0 && saoleiDianzhanService.findList(dianzhan) != null){
                user.setZan(true);
            }else{
                user.setZan(false);
            }
            user.setStatus(pkController.getStatus(user.getId()).getData());
        }


        return new Result<List<User>>(true, StatusCode.OK.getCode(),"查询成功",resultList) ;
    }

    /***
     * 获取积分排行榜
     * @return
     */
    @Operation(summary = "获取积分排行榜",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @GetMapping("/count/{player}")
    public Result<List<User>> findJiFengByDESC(@PathVariable Long player){
        //调用SaoleiUserService实现查询所有SaoleiUser
        List<User> list = saoleiUserService.findJiFengByDESC();
        // 判断用户是否点赞
        for (User user : list) {
            Dianzhan dianzhan = new Dianzhan();
            dianzhan.setProvider(player);
            dianzhan.setReceiver(user.getId());
            if(saoleiDianzhanService.findList(dianzhan).size() > 0 && saoleiDianzhanService.findList(dianzhan) != null){
                user.setZan(true);
            }else{
                user.setZan(false);
            }
            user.setStatus(pkController.getStatus(user.getId()).getData());
        }
        return new Result<List<User>>(true, StatusCode.OK.getCode(),"查询成功",list) ;
    }

    /***
     * 获取点赞排行榜
     * @return
     */
    @Operation(summary = "获取点赞排行榜",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @GetMapping("/dianZan")
    public Result<List<User>> findDianZhanByDESC(){
        //调用SaoleiUserService实现查询所有SaoleiUser
        List<User> list = saoleiUserService.findDianZanByDESC();
        for (User user : list) {
            user.setStatus(pkController.getStatus(user.getId()).getData());
        }
        return new Result<List<User>>(true, StatusCode.OK.getCode(),"查询成功",list) ;
    }

    /***
     * 获取pk排行榜
     * @return
     */
    @Operation(summary = "获取pk排行榜",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @GetMapping("/pkTotal/{player}")
    public Result<List<User>> findPkByDESC(@PathVariable Long player){
        //调用SaoleiUserService实现查询所有SaoleiUser
        List<User> list = saoleiUserService.findPkByDESC();
        // 判断用户是否点赞
        for (User user : list) {
            Dianzhan dianzhan = new Dianzhan();
            dianzhan.setProvider(player);
            dianzhan.setReceiver(user.getId());
            if(saoleiDianzhanService.findList(dianzhan).size() > 0 && saoleiDianzhanService.findList(dianzhan) != null){
                user.setZan(true);
            }else{
                user.setZan(false);
            }
            user.setStatus(pkController.getStatus(user.getId()).getData());
        }
        return new Result<List<User>>(true, StatusCode.OK.getCode(),"查询成功",list) ;
    }

    /***
     * 获取总场次前十排名
     * @return
     */
    @Operation(summary = "获取总场次前十排名",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @GetMapping("/gameTotal/{player}")
    public Result<List<User>> findGameTotalByDESC(@PathVariable Long player){
        //调用SaoleiUserService实现查询所有SaoleiUser
        List<User> list = saoleiUserService.findGameTotalByDESC();
        // 判断用户是否点赞
        for (User user : list) {
            Dianzhan dianzhan = new Dianzhan();
            dianzhan.setProvider(player);
            dianzhan.setReceiver(user.getId());
            if(saoleiDianzhanService.findList(dianzhan).size() > 0 && saoleiDianzhanService.findList(dianzhan) != null){
                user.setZan(true);
            }else{
                user.setZan(false);
            }
            user.setStatus(pkController.getStatus(user.getId()).getData());
        }

        return new Result<List<User>>(true, StatusCode.OK.getCode(),"查询成功",list) ;
    }

    /***
     * 增加pk场次
     * @return
     */
    @Operation(summary = "增加pk场次",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @PostMapping("/pkTotal/{playerId}/{count}")
    public Result addPkTotal(@PathVariable Long playerId, @PathVariable Integer count){
        User user = saoleiUserService.findById(playerId);
        if(user != null){
            if(count > 0){
                // 大于零表示胜利
                user.setPkTotal(user.getPkTotal()+1);
            }
            user.setCount(user.getCount()+count);
            saoleiUserService.updateById(user);
            return new Result(true, StatusCode.OK.getCode(),"修改成功") ;
        }else {
            return new Result(true, StatusCode.ERROR.getCode(),"修改失败,用户不存在") ;
        }
    }


    /***
     * 设置用户挑战状态
     * @return
     */
    @Operation(summary = "增加pk场次",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @PostMapping("/pkStatus/{playerId}/{status}")
    public Result setPkStatus(@PathVariable Long playerId,@PathVariable String status){
        User user = saoleiUserService.findById(playerId);
        if(user != null){
            user.setPkStatus(status);
            saoleiUserService.updateById(user);
            return new Result(true, StatusCode.OK.getCode(),"修改成功") ;
        }else {
            return new Result(true, StatusCode.ERROR.getCode(),"修改失败,用户不存在") ;
        }
    }



}
